package nciae.db.controller;


import nciae.db.common.CommonResult;
import nciae.db.pojo.dto.PasswordChangeRequestDto;
import nciae.db.pojo.entity.User;
import nciae.db.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

@Controller
public class UserController {
    @Autowired
    private UserService userService;
/*
* 用户登录与认证
调用 userService.checkUser 方法验证用户名和密码。
如果验证成功，将用户信息存入 HttpSession。
返回登录结果。
* */
    @RequestMapping(value = "/login.do",method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<User> login(@RequestParam String username, @RequestParam String password, HttpSession session){
        System.out.println(username + password);
        CommonResult<User> rs = userService.checkUser(username,password,session);
        if(rs.getCode()==0){
            session.setAttribute("user",rs.getData());//添加session
        }else{

        }
        return rs;

    }
    /*
    * 功能：处理用户注销请求。
    逻辑：
    从 HttpSession 中移除用户信息。
    返回注销成功的响应。
    * */
    @RequestMapping("/user/logout")
    @ResponseBody
    public CommonResult<Integer> logout(HttpSession session){
        session.removeAttribute("user");
        CommonResult rs = new CommonResult();
        rs.setCode(0);
        rs.setMsg("注销成功");
        return rs;
    }
    /*
    * 功能：获取当前登录用户的ID。
        逻辑：
        从 HttpSession 中获取当前登录用户。
        返回用户的ID。
        * */
    @RequestMapping("/user/findUserName")
    @ResponseBody
    public CommonResult<Integer> findUserName(HttpSession session) {
        return findUser(session);
    }

    @RequestMapping("/user/findChargerName")
    @ResponseBody
    public CommonResult<Integer> findChargerName(HttpSession session) {
        return findUser(session);
    }

    /**
     * 获取id
     * @param session
     * @return
     */
    private CommonResult<Integer> findUser(HttpSession session) {
        CommonResult<Integer> rs = new CommonResult<>();
        try {
            User user = (User) session.getAttribute("user");
            if (user != null) {
                Integer userId = user.getId();
                rs.setCode(0);
                rs.setMsg("查询成功");
                rs.setData(userId);
                System.out.println("设置的数据为：" + userId);
            } else {
                rs.setCode(1);
                rs.setMsg("未找到用户信息");
            }
        } catch (Exception e) {
            rs.setCode(-1);
            rs.setMsg("发生错误：" + e.getMessage());
        }
        return rs;
    }
    /*
    * 获取当前登录用户的用户名。*/
    @RequestMapping("/user/findExpertName")
    @ResponseBody
    public CommonResult<String> findExpertName(HttpSession session) {
        CommonResult<String> rs = new CommonResult<>();
        try {
            User user = (User) session.getAttribute("user");
            if (user!= null) {
                String expertId = user.getUserName();
                rs.setCode(0);
                rs.setMsg("查询成功");
                rs.setData(expertId);
            } else {
                rs.setCode(1);
                rs.setMsg("未找到用户信息");
            }
        } catch (Exception e) {
            rs.setCode(-1);
            rs.setMsg("发生错误：" + e.getMessage());
        }
        return rs;
    }
    /*根据真实姓名查找用户的ID*/
    @RequestMapping("/user/findUserId")
    @ResponseBody
    public CommonResult<Integer> findUserId(HttpServletRequest request) {
        String chargerName = request.getParameter("chargerName");
        System.out.println(chargerName);
        return userService.findUserId(chargerName);
    }
    /*返回用户管理页面的视图。*/
    @GetMapping("/user/index")
    public String index(){
        return "user/index";
    }

    /*返回用户表单页面，用于编辑用户。
    * 逻辑：
    创建一个新的 User 对象。
    设置 id 为 0 表示新增操作。
    返回 user/form 视图，并将 User 对象添加到模型中。*/
    @GetMapping("/user/form")
    public ModelAndView form(Integer id, Model model){
        User user;
        user = new User();
        user.setId(0);
        ModelAndView view = new ModelAndView();
        view.setViewName("user/form");
        model.addAttribute("model",user);
        return view;
    }
    /*功能：返回用户表单页面，用于编辑用户。
    逻辑：
    根据 id 获取用户信息。
    返回 user/editForm 视图，并将 User 对象添加到模型中。*/
    @GetMapping("/user/editForm")
    public ModelAndView editForm(Integer id, Model model){
        User user;
        user = userService.getUserInfo(id);
        ModelAndView view = new ModelAndView();
        view.setViewName("user/editForm");
        model.addAttribute("model",user);
        return view;
    }
    /*
    * 分页查询*/
    @ResponseBody
    @RequestMapping("/user/list")
    public CommonResult<List<User>> list(int page, int limit, String userName, String realName ,String role,String tel){
        CommonResult rs = userService.search(userName,realName,role,tel,page,limit);
        return rs;
    }
    /*保存用户及新增和更新*/
    @ResponseBody
    @PostMapping("/user/save")
    public CommonResult save(@RequestBody User user){
        User model = user;
        if(model.getId()==0){
            model.setUserPwd("123456");
        }else{
            model = userService.getUserInfo(model.getId());
            model.setUserName(user.getUserName());
            model.setRealName(user.getRealName());
            model.setRole(user.getRole());
            model.setTel(user.getTel());
            model.setEmail(user.getEmail());
        }
        return userService.save(model);
    }
    /*删除用户*/
    @ResponseBody
    @PostMapping("/user/del")
    public CommonResult<Boolean> del(Integer id){
        return userService.delete(id);
    }
    /*重置用户密码为默认值（123456）。*/
    @ResponseBody
    @PostMapping("/user/reset_password")
    public CommonResult resetPassword(Integer id){
        return userService.resetPwd(id);
    }

    @GetMapping("/user/changepwd")
    public ModelAndView changePwd(){
        ModelAndView view = new ModelAndView();
        view.setViewName("/user/changepwd");
        return view;
    }

    @ResponseBody
    @PostMapping("/user/changepwd")
    public CommonResult changeNewPwd(HttpSession session,String old_pwd,String new_pwd){
        User user = (User) session.getAttribute("user");
        System.out.println(user);
        return userService.changePwd(user.getId(),old_pwd,new_pwd);
    }

    @ResponseBody
    @PostMapping("/user/batchImport")
    public CommonResult<Integer> batchImport(@RequestParam("file") MultipartFile file){
        return userService.batchImport(file);
    }

    @GetMapping("/teachers")
    @ResponseBody
    public CommonResult GetCharger(){
        return userService.getUsersByRole("班主任");
    }

    @ResponseBody
    @GetMapping("/user/listChargerName")
    public CommonResult<List<String>> listChargerName() {
        return userService.listChargerName();
    }

   @GetMapping ("/admin/changePwdform")
   public ModelAndView changePwdform(){
        return new ModelAndView("admin/changePwdform");
   }

    @ResponseBody
    @PostMapping("/user/changePassword")
    public CommonResult<User> ChangePassword(HttpSession session,@RequestBody PasswordChangeRequestDto request) {
        User user=(User) session.getAttribute("user");
        CommonResult rs=new CommonResult();
        if (user==null){
             rs.setCode(-1);
             rs.setMsg("用户未登录，请先登录");
             return rs;
        }
        return userService.changePwd(user.getId(),request.getOldPassword(),request.getNewPassword());
    }




    @GetMapping("/admin/userInfoform")
    public ModelAndView userInfoform(HttpSession session) {
        ModelAndView modelAndView = new ModelAndView("admin/userInfoform");

        // 从 Session 获取用户
        User user = (User) session.getAttribute("user");

        if (user == null) {
            // 如果用户未登录，重定向到登录页面
            modelAndView.setViewName("redirect:/login");
            return modelAndView;
        }

        // 从数据库获取用户信息
        User userInfo = userService.getUserInfo(user.getId());

        if (userInfo != null) {
            // 将用户信息添加到模型中
            modelAndView.addObject("user", userInfo);
        } else {
            // 如果未查询到用户信息，可以返回错误页面或提示
            modelAndView.setViewName("error/404");
        }

        return modelAndView;
    }


    @ResponseBody
    @PostMapping("/user/userInfo")
    public CommonResult<User> UserInfo(HttpSession session) {
        User user1 = (User) session.getAttribute("user");
        CommonResult<User> rs = new CommonResult<>();

        if (user1 == null) {
            rs.setCode(-1);
            rs.setMsg("用户未登录，请先登录");
            return rs;
        }

        // 查询用户信息
        User userInfo = userService.getUserInfo(user1.getId());

        if (userInfo != null) {
            rs.setCode(0);
            rs.setMsg("查询成功");
            rs.setData(userInfo);
        } else {
            rs.setCode(-1);
            rs.setMsg("查询失败，未找到用户信息");
        }

        return rs;
    }

    @ResponseBody
    @PostMapping("/user/userIsAdmin")
    public CommonResult<Boolean> UserIsAdmin(HttpSession session) {
        User user1 = (User) session.getAttribute("user");
        CommonResult<Boolean> rs = new CommonResult<>();

        if (user1 == null) {
            rs.setCode(-1);
            rs.setMsg("用户未登录，请先登录");
            return rs;
        }

        // 查询用户是否为管理员

        boolean isAdmin = userService.getUserIsAdmin(user1.getId());

        rs.setCode(0);
        rs.setMsg("查询成功");
        rs.setData(isAdmin);

        return rs;
    }
    @ResponseBody
    @GetMapping("/category/statistics")
    public Map<String, Integer> getUserCategoryStatistics() {
        return userService.getUserCategoryStatistics();
    }
}
